import { useGlobSetting } from "@/hooks/setting";
import { Base64 } from "js-base64";

const globalSetting = useGlobSetting()

/**
 * 将对象添加当作参数拼接到URL上面
 * @param baseUrl 需要拼接的url
 * @param obj 参数对象
 * @returns {string} 拼接后的对象
 * 例子:
 *  let obj = {a: '3', b: '4'}
 *  setObjToUrlParams('www.baidu.com', obj)
 *  ==>www.baidu.com?a=3&b=4
 */
export function setObjToUrlParams(baseUrl: string, obj: object): string {
  let parameters = '';
  let url = '';
  for (const key in obj) {
    parameters += key + '=' + encodeURIComponent(obj[key]) + '&';
  }
  parameters = parameters.replace(/&$/, '');
  if (/\?$/.test(baseUrl)) {
    url = baseUrl + parameters;
  } else {
    url = baseUrl.replace(/\/?$/, '?') + parameters;
  }
  return url;
}

/**
 * 获取该网页的根网址 => http://localhost:80
 */
export function getRootUrl(): string {
  // host -> 已经包含了端口
  return `${window.location.protocol}//${window.location.host}`
}

/**
 * 生成用于请求后端接口的url => http://localhost:80/api/test
 * @param api
 */
export function generatorApiUrl(api: string): string {
  return getRootUrl() + globalSetting.urlPrefix + api;
}

/**
 * 使用 Base64编码生成 KkFileView 可识别的url
 * @param url
 */
export function encodePreviewUrl(url: string): string {
  return encodeURIComponent(Base64.encode(url));
}

/**
 * 判断是否是url
 * @param path
 */
export function isUrl(path: string): boolean {
  const reg = /^(https|http)?:\/\/|^\/\//;
  return reg.test(path);
}
